'use strict';

angular.module('App').controller('SecretManageController', ['$scope', '$state', '$http', 'ParameterService', 'BaseSocket', 'BaseFunction', 'BaseClass', 'BaseModule', 'BaseEnum', 'BaseService', 'EntityService', '$location', 'Authentication',
    function($scope, $state, $http, ParameterService, BaseSocket, BaseFunction, BaseClass, BaseModule, BaseEnum, BaseService, EntityService, $location, Authentication) {
        $scope.DeviceTypeEnum = BaseFunction.getEnum('AppEnum.DeviceType');

        // 授权服务地址
        $scope.licenceURL = "";

        var serverUrl = "";

        var publicSocket;

        BaseSocket.connect(function(skt){
            publicSocket = skt;
        });

        var round = new BaseClass.Round();

        BaseModule.initModule($scope, '_App');

        $scope.Module._App.PageSize = 15;

        BaseModule.initModule($scope, 'App');

        $scope.Module.App.LoadMode = BaseEnum.LoadMode.CacheAndNoPaging;

        $scope.DownloadStatus = {
            No: 0,              //最新版本
            Downloadable: 1,    //可下载
            Updatable: 2,       //可更新
            Downloading: 3      //下载中
        };

        licenceQuery();

        function licenceQuery() {
            ParameterService.getParameterValue(null, 'DCServer', function(DCUrl){
                if(!DCUrl) {
                    BaseFunction.tip('智能工厂服务器地址不正确，请在【网关服务器】->【系统管理】->【参数设置】中配置！');
                } else {
                    // 根据DCUrl查询licenceURL
                    var reqData = {
                        Code: 'LicenseUrl',
                    };
                    var PrintAddressURL = 'http://' + DCUrl + '/api/exteralService/getPrintAddress';
                    BaseFunction.httpRequest(PrintAddressURL, reqData, function(licence){
                        if(!licence) {
                            BaseFunction.tip('许可服务器地址查询失败，请检查【智能工厂】->【系统管理】->【参数设置】中的许可服务器配置！');
                        } else {
                            $scope.licenceURL = licence;
                            $http({
                                method : 'POST',
                                url : 'http://' + $scope.licenceURL + '/ZNZZLicence/api/licence/query',
                            }).then(function (result) {
                                if(!!result) {
                                    var filters = {};
                                    var Data = result.data.Data;
                                    var Qty = Data['Qty'];
                                    for(var key in Qty) {
                                        filters[key] = Qty[key];
                                    }
                                    var Modules = Data['Modules'];
                                    for(var x = 0; x < Modules.length; x++) {
                                        var item = Modules[x];
                                        filters[item['Code']] = item['Value'];
                                    }
                                    var Apps = Data['Apps'];
                                    for(var x = 0; x < Apps.length; x++) {
                                        var item = Apps[x];
                                        filters[item['Code']] = item['Value'];
                                    }
                                    for (var index = 0; index < $scope.Module._App.Records.length; index++) {
                                        var item = $scope.Module._App.Records[index];
                                        var featureID = item['featureID'];
                                        item['featureValue'] = filters[featureID];
                                    }
                                }
                                $scope.Module._App.emitOnLoadEvent();
                            },function (err) {
                                BaseFunction.tip('licence解析失败！');
                            });
                        }
                    });

                }
            });
        };

        /**
         * znzzlicence
         * 调用licence服务导出环境信息
         */
        $scope.envExport = function() {
            $http({
                method : 'POST',
                url : 'http://' + $scope.licenceURL + '/ZNZZLicence/api/licence/export',
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).then(function (result) {
                BaseFunction.tip(result.data.msg);
            },function (err) {
                BaseFunction.tip('硬件信息导出失败，请检查.dll路径与授权服务地址是否正确！');
            });
        };

        /**
         * znzzlicence
         * 调用licence服务上传文件
         */
        $scope.uploadFile = function() {
            if(file.files[0] == undefined) {
                BaseFunction.tip('请选择上传文件！');
                return;
            }
            var formData = new FormData();
            formData.append('file', file.files[0]);
            $http.post('http://' + $scope.licenceURL + '/ZNZZLicence/api/licence/upload', formData, {
                transformRequest: function(data, headersGetterFunction) {
                    return data;
                },
                headers: { 'Content-Type': undefined }
            }).success(function(data, status) {
                BaseFunction.tip(data.msg);
            }).error(function(data, status) {
                BaseFunction.tip('上传文件失败，请检查licence文件正确性！');
            });
        };

        $scope.btnSyncAll = function(){
            //获取内网地址
            BaseService.getSysConstValue('Intranet', function(dataUrl){
                var serverUrl = dataUrl.HostName + ':' + dataUrl.Port;
                $scope.Module.App.find({IsEffective: true, IsSync: {$ne: true}}, null, null, function(records){
                    if(records.length > 0){
                        for(var i=0; i<records.length; i++){
                            delete records[i]["_id"];
                            delete records[i]["RowStatus"];
                            delete records[i]["IsHide"];
                            delete records[i]["IsSelected"];
                            delete records[i]["IsSync"];
                        }
                        BaseFunction.httpRequest(serverUrl + "/api/App/updateApps", {Apps: records}, function(data){
                            EntityService.updateByValue('App', {IsEffective: true}, {$set: {IsSync: true}}, function(data){
                                $state.reload();
                                BaseFunction.tip("同步完成", "操作提示");
                            });
                        });
                    }
                });
            });
        };

        /**
         * 下载全部，只下载当前页数据，跨页会有进度条div没有被创建的问题
         */
        $scope.btnDownloadAll = function(){
            var tables = document.getElementsByTagName('table');
            for(var i=0; i<tables.length; i++){
                if(tables[i].getAttribute('class') == 'TableBody'){
                    if(tables[i].rows.length > 0) {
                        BaseFunction.loading(true);
                        var downCount = 0;
                        var downComplete = function () {
                            downCount++;
                            if (downCount == tables[i].rows.length) {
                                BaseFunction.loading(false);
                            }
                        }
                        for (var j = 0; j < tables[i].rows.length; j++) {
                            $scope.download(
                                $scope.Module._App.findRecordById(tables[i].rows[j].getAttribute('key')),
                                tables[i].rows[j].cells[tables[i].rows[0].cells.length - 1].children[0].children[3],
                                downComplete
                            );
                        }
                    }
                    break;
                }
            }
        };

        $scope.download = function(record, scheduleDiv, completeFun){
            //全部下载时，用来判断不用下载的记录
            if(record.DownloadStatus == $scope.DownloadStatus.No){
                if(completeFun){
                    completeFun();
                }
                return;
            }

            var serverPath = serverUrl + "/api/App/getFileStream";

            var focusedRecord= null;    // 当前数据库记录
            if(record.CurrentRecordId != null){
                focusedRecord = $scope.Module.App.findRecordById(record.CurrentRecordId);
                $scope.Module.App.FocusedRecord = focusedRecord;
            }

            var isErrDisplayImg = false,
                isUploadDisplayImg = false; //上传动作是否完成
            if(record.DisplayImage != null && record.DisplayImage != undefined && record.DisplayImage.trim() != ""
                && (focusedRecord == null || record.DisplayImage != focusedRecord.DisplayImage)){
                var deleteDownDisplayImg = null;    //删除显示图片文件名
                if(focusedRecord != null){
                    deleteDownDisplayImg = focusedRecord.MouseDownImage;
                }

                BaseService.downloadFile(serverPath, record.DisplayImage,
                 null, deleteDownDisplayImg, null, function(data){
                    if(data.Error){
                        isErrDisplayImg = true;
                        console.log("下载显示图标" + record.DisplayImage + "出错，可尝试重现下载\n\r出错信息：" + data.Error.message);
                    }
                    isUploadDisplayImg = true;
                    updateReord();
                });
            }
            else{
                isUploadDisplayImg = true;
            }

            var isErrMouseImg = false,
                isUploadDownMouseImg = false;   //上传动作是否完成         
            if(record.MouseDownImage != null && record.MouseDownImage != undefined && record.MouseDownImage.trim() != ""
                && (focusedRecord == null || record.MouseDownImage != focusedRecord.MouseDownImage)){
                var deleteDownMouseImg = null;      //删除鼠标按下图片文件名
                if(focusedRecord != null){
                    deleteDownMouseImg = focusedRecord.MouseDownImage;
                }

                BaseService.downloadFile(serverPath, record.MouseDownImage,
                 null, deleteDownMouseImg, null, function(data){
                    if(data.Error){
                        isErrMouseImg = true;
                        console.log("下载按下图标" + record.MouseDownImage + "出错，可尝试重现下载\n\r出错信息：" + data.Error.message);
                    }
                    isUploadDownMouseImg = true; 
                    updateReord();
                });
            }
            else{
                isUploadDownMouseImg = true; 
            }

            var isErrDownFile = false,
                isUploadFile = false;   //上传动作是否完成
            if(record.FileName != null && record.FileName != undefined && record.FileName.trim() != ""
                && (focusedRecord == null || record.FileName != focusedRecord.FileName)){
                record.DownloadStatus = $scope.DownloadStatus.Downloading;  //下载中
                //获取上传进度条Element
                var divElement = null;
                if(event.srcElement.innerText == "全部下载"){
                    divElement = scheduleDiv;
                } 
                else{
                    divElement = event.srcElement.parentElement;
                    while(divElement.tagName.toLowerCase() != "div"){
                        divElement = divElement.parentElement;
                    }
                    divElement =  divElement.children[3];
                }

                if(divElement != null){
                    divElement.innerText = "0%";
                    divElement.style.width = "0%";
                    divElement.style.display = '';
                }

                var deleteFileName = null;      //删除文件名
                if(focusedRecord != null){
                    deleteDownMouseImg = focusedRecord.FileName;
                }

                var downloadSize = 0;                
                publicSocket.on(record.FileName + "_DownloadSize", function(size) {
                    downloadSize += size;
                    // Circle(downloadSize / record.FileSize);
                    if(divElement != null){
                        divElement.innerText = round.formatPercent(downloadSize / record.FileSize);
                        divElement.style.width = (downloadSize / record.FileSize * 100).toString() + "%";
                    }
                });
                publicSocket.on(record.FileName + "_DownloadComplete", function(IsDownload) {
                    if(IsDownload){
                        //Circle(1);
                        if(divElement != null){
                            divElement.style.width = "100%";
                            divElement.innerText = "100%";
                        }
                    }
                    else{
                        if(divElement != null){
                            divElement.style.width = "0%";
                            divElement.innerText = "";
                        }
                        console.log("下载App包" + record.FileName + "出错，可尝试重现下载");
                    }

                    // divElement.style.display = 'none';
                });

                BaseService.downloadFile(serverPath, record.FileName, null, deleteFileName, publicSocket.Socket.id, function(data){
                    if(data.Error){
                        isErrDownFile = true;
                        console.log("下载App包" + record.FileName + "出错，可尝试重现下载\n\r出错信息：" + data.Error.message);
                    }
                    isUploadFile = true;
                    updateReord();
                });
            }
            else{
                isUploadFile = true;
                if(completeFun){
                    completeFun();
                }
            }

            var updateReord = function(){
                if(isUploadFile && isUploadDownMouseImg && isUploadDisplayImg){
                    if(!isErrDownFile || !isErrMouseImg || !isErrDisplayImg){
                        if(focusedRecord == null){
                            //新增Record
                            focusedRecord = $scope.Module.App.add();
                        }
                        else{
                            focusedRecord.RowStatus = BaseEnum.RowStatus.Modify.Value;
                        }
                        focusedRecord["AppID"] = record.AppID;
                        focusedRecord["Name"] = record.Name;
                        if(!isErrDownFile && !isErrMouseImg && !isErrDisplayImg){
                            focusedRecord["Version"] = record.Version;
                        }
                        if(!isErrDownFile){
                            focusedRecord["FileName"] = record.FileName;
                            focusedRecord["FileSize"] = record.FileSize;
                        }
                        if(!isErrDisplayImg){
                            focusedRecord["DisplayImage"] = record.DisplayImage;
                            focusedRecord["DisplayImageSize"] = record.DisplayImageSize;
                        }
                        if(!isErrMouseImg){
                            focusedRecord["MouseDownImage"] = record.MouseDownImage;
                            focusedRecord["MouseDownImageSize"] = record.MouseDownImageSize;
                        }
                        focusedRecord["Describe"] = record.Describe;
                        focusedRecord["Remark"] = record.Remark;
                        focusedRecord["IsEffective"] = record.IsEffective;
                        focusedRecord["IsShared"] = record.IsShared;
                        focusedRecord["IsSync"] = false;
                        focusedRecord["Type"] = record.Type;

                        $scope.Module.App.save(function(){
                            if(!isErrDownFile && !isErrMouseImg && !isErrDisplayImg){
                                record["CurrentVersion"] = focusedRecord.Version;
                                record.DownloadStatus = $scope.DownloadStatus.No;
                                record.IsSync = false;
                                $scope.Module._App.emitRowsDataChangeEvent([record]);
                            }
                            else{
                                record.DownloadStatus = $scope.DownloadStatus.Updatable;
                            }
                        });
                    }
                }

                if(completeFun){
                    completeFun();
                }
            };
        };

        $scope.delete = function(record){
            if($scope.Module._App.FocusedRecord.CurrentRecordId != null){
                $scope.Module.App.FocusedRecord = $scope.Module.App.findRecordById($scope.Module._App.FocusedRecord.CurrentRecordId);
                $scope.Module.App.delete(function(){
                    $scope.Module._App.FocusedRecord.CurrentRecordId = null;
                    $scope.Module._App.FocusedRecord.CurrentVersion = "";
                    $scope.Module._App.FocusedRecord.DownloadStatus = $scope.DownloadStatus.Downloadable;
                });
            }
        };

        var DownloadFile = function(serverPath, downloadPath, downloadFileName, uploadPath, fileName, fileSize, deleteFileName, isDownloadable, isUpdatable){
            this.ServerPath = serverPath;
            this.DownloadPath = null;
            this.DownloadFileName = downloadFileName;
            this.UploadPath = null;
            this.FileName = null;
            this.FileSize = fileSize;
            this.DeleteFileName = deleteFileName;
            this.IsDownloadable = isDownloadable;
            this.IsUpdatable = isUpdatable;

            this.CircleElement = null;
            this.IsDownloading = false;

            if(this.ServerPath == null || this.ServerPath == undefined){
                // var serverUrl = "http://10.1.217.3:3000";
                // this.ServerPath = serverUrl + "/api/base/getFileStream";
            }
            if(downloadPath != null && downloadPath != undefined){
                this.DownloadPath = downloadPath;
            }
            if(uploadPath != null && uploadPath != undefined){
                this.UploadPath = uploadPath;
            }
            if(fileName != null && fileName != undefined){
                this.FileName = fileName;
            }

            this.download = function(downloadHandle){
                this.IsDownloading = true;

                var publicSocket = null;
                if(this.FileSize != null && this.FileSize != undefined && this.FileSize > 0){
                    this.Circle(0);
                    this.CircleElement = event.srcElement.parentElement.children[2].children[0];
                    var downloadSize = 0;
                    var self = this;
                    BaseSocket.connect(function(skt){
                        publicSocket = skt;
                        publicSocket.on(self.FileName + "_DownloadSize", function(size) {
                            downloadSize += size;
                            self.Circle(downloadSize / $scope.filesize);
                        });
                        publicSocket.on(self.FileName + "_DownloadComplete", function(IsDownload) {
                            if(IsDownload){
                                self.Circle(1);
                                self.IsDownloadable = false;
                                self.IsUpdatable = false;
                            }
                            else{
                                BaseFunction.alert("下载出错，文件没有下载完，请重新下载", "下载失败");
                            }
                            self.IsDownloading = false;
                        });


                        BaseService.downloadFile(self.ServerPath, self.DownloadPath, self.DownloadFileName, self.UploadPath,
                         self.FileName, self.DeleteFileName, publicSocket.Socket.id, function(data){
                            if(data.Error){
                                BaseFunction.alert(data.Error.message, data.Error.title);
                            }
                            else{
                                if(downloadHandle){
                                    downloadHandle(data);
                                }
                            }
                        });
                    });
                }
            };

            this.Circle = function(progress){
                var ctx = this.CircleElement.getContext("2d");
                ctx.lineWidth = 2;
                ctx.strokeStyle = "#0000ff";
                // ctx.font = '10pt';
                // ctx.fillText("5%", 7, 17);
                ctx.beginPath();
                ctx.arc(13, 13,  11, Math.PI * 1.5, (-0.5 + 2 * progress + 2) * Math.PI, false);
                ctx.stroke();
            };
        };

        // licence内容：类别、特征ID、特征名称、特征值、相关应用
        $scope.Module._App.Records  = [
            {type:'其他', featureID:'U1', featureName:'采集终端注册', featureValue:'', app:''},
            {type:'其他', featureID:'U2', featureName:'交互终端注册', featureValue:'', app:''},
            {type:'其他', featureID:'U3', featureName:'展示终端注册', featureValue:'', app:''},
            {type:'其他', featureID:'U4', featureName:'应用平台', featureValue:'', app:''},
            {type:'其他', featureID:'U5', featureName:'管理平台', featureValue:'', app:''},
            {type:'其他', featureID:'U6', featureName:'IDE', featureValue:'', app:''},
            {type:'后台系统', featureID:'U7', featureName:'车间计划', featureValue:'', app:'生产订单、工序作业计划、生成作业计划、完工计划（产出计划）、设备产能表'},
            {type:'后台系统', featureID:'UA', featureName:'品质管理', featureValue:'', app:''},
            {type:'前端应用', featureID:'UB', featureName:'来料检验', featureValue:'', app:''},
            {type:'前端应用', featureID:'UC', featureName:'过程检验', featureValue:'', app:'指标检验（pad/pda）、缺陷检验（pad/pda）、批次判定、品质判定、品质特裁'},
            {type:'前端应用', featureID:'UD', featureName:'完工检验', featureValue:'', app:''},
            {type:'前端应用', featureID:'UE', featureName:'首件检验', featureValue:'', app:'首件检验、首件确认'},
            {type:'前端应用', featureID:'UF', featureName:'巡检', featureValue:'', app:'巡检作业（pad/pda）'},
            {type:'前端应用', featureID:'UG', featureName:'不良处理', featureValue:'', app:''},
            {type:'前端应用', featureID:'UH', featureName:'工段交接', featureValue:'', app:'要货看板、备货看板、交接检查、交接确认'},
            {type:'前端应用', featureID:'UI', featureName:'工步交接', featureValue:'', app:''},
            {type:'前端应用', featureID:'UJ', featureName:'物流配送', featureValue:'', app:''},
            {type:'前端应用', featureID:'UK', featureName:'成品下线', featureValue:'', app:'成品入库、装箱入库'},
            {type:'后台系统', featureID:'UL', featureName:'齐套管理', featureValue:'', app:''},
            {type:'前端应用', featureID:'UM', featureName:'生产领用', featureValue:'', app:''},
            {type:'后台系统', featureID:'UN', featureName:'设备台账', featureValue:'', app:'设备台账、设备参数模板、设备参数绑定、物料工艺参数、工艺参数模板'},
            {type:'后台系统', featureID:'UO', featureName:'维修保养计划', featureValue:'', app:''},
            {type:'前端应用', featureID:'UP', featureName:'日常管理', featureValue:'', app:'设备运行记录'},
            {type:'前端应用', featureID:'UQ', featureName:'维修管理', featureValue:'', app:''},
            {type:'后台系统', featureID:'UR', featureName:'备品备件', featureValue:'', app:''},
            {type:'后台系统', featureID:'US', featureName:'人员能力管理', featureValue:'', app:''},
            {type:'后台系统', featureID:'UT', featureName:'人员绩效', featureValue:'', app:''},
            {type:'后台系统', featureID:'UU', featureName:'模具管理', featureValue:'', app:'模具台账、模具分类维护'},
            {type:'后台系统', featureID:'UV', featureName:'刀具管理', featureValue:'', app:'刀具台账、刀具分类维护'},
            {type:'后台系统', featureID:'UW', featureName:'夹具管理', featureValue:'', app:'夹具台账、夹具分类维护'},
            {type:'前端应用', featureID:'UX', featureName:'设备状态看板', featureValue:'', app:''},
            {type:'前端应用', featureID:'UY', featureName:'生产进度看板', featureValue:'', app:'车间进度看板'},
            {type:'前端应用', featureID:'UZ', featureName:'生产良率看板', featureValue:'', app:''},
            {type:'前端应用', featureID:'EA', featureName:'测量采集', featureValue:'', app:'磅重、周径测量'},
            {type:'前端应用', featureID:'EB', featureName:'生产异常', featureValue:'', app:''},
            {type:'前端应用', featureID:'EC', featureName:'质量异常', featureValue:'', app:''},
            {type:'前端应用', featureID:'ED', featureName:'设备异常', featureValue:'', app:''},
            {type:'前端应用', featureID:'EE', featureName:'环境异常', featureValue:'', app:''},
            {type:'前端应用', featureID:'EF', featureName:'系统异常', featureValue:'', app:''},
            {type:'前端应用', featureID:'EG', featureName:'电子作业指导书', featureValue:'', app:''},
            {type:'其他', featureID:'EH', featureName:'多工厂', featureValue:'', app:''},
            {type:'其他', featureID:'EI', featureName:'基础数据集成', featureValue:'', app:''},
            {type:'其他', featureID:'EJ', featureName:'生产计划集成', featureValue:'', app:''},
            {type:'其他', featureID:'EK', featureName:'物料消耗集成', featureValue:'', app:''},
            {type:'其他', featureID:'EL', featureName:'物联组件', featureValue:'', app:''},
            {type:'后台系统', featureID:'EM', featureName:'能力负载', featureValue:'', app:''},
            {type:'后台系统', featureID:'EN', featureName:'有限能力辅助排程', featureValue:'', app:''},
            {type:'后台系统', featureID:'EO', featureName:'机台派工-Portal', featureValue:'', app:''},
            {type:'前端应用', featureID:'EP', featureName:'机台派工-移动', featureValue:'', app:''},
            {type:'前端应用', featureID:'EQ', featureName:'任务超市', featureValue:'', app:'任务超市'},
            {type:'前端应用', featureID:'ER', featureName:'机台报工', featureValue:'', app:'任务工作台、任务报工（pad）'},
            {type:'前端应用', featureID:'ES', featureName:'工段报工', featureValue:'', app:'任务执行'},
            {type:'前端应用', featureID:'ET', featureName:'工步报工', featureValue:'', app:''},
            {type:'前端应用', featureID:'EU', featureName:'工票报工', featureValue:'', app:'任务报工（pda）'},
            {type:'免费应用', featureID:'FREE', featureName:'工票报工', featureValue:'1', app:'合格品检验、物流配送、不良品检验、标签打印、镭射标绑定、' +
            '单品流水、芯片更替、备料产量看板、尺寸绑定、批次绑定、外观绑定、智能工厂HD、示例应用、智能工厂PDA、示例应用、智能工厂TV、示例应用'}
        ];

    }
]);
